package edu.uoc.tdp.pac4.client.Academic;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import edu.uoc.tdp.pac4.beans.Course;
import edu.uoc.tdp.pac4.beans.Group;
import edu.uoc.tdp.pac4.beans.Shift;
import edu.uoc.tdp.pac4.client.ClientConnectionHelper;
import edu.uoc.tdp.pac4.common.AcademicManagementInterface;
import edu.uoc.tdp.pac4.common.util.LanguageUtils;

/**
 * Creates the JFrame to save a new group
 * 
 * @author Laia
 * 
 */
public class Group_SaveGroup extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	AcademicManagementInterface academicManagement;
	ClientConnectionHelper connectionHelper_;

	Group_ViewGroup group_ViewGroup;

	private JPanel contentPane;
	private JTextField textFieldMax;
	private JTextField textFieldStart;
	private JTextField textFieldEnd;
	private JRadioButton rdbtnActiu;
	private JRadioButton rdbtnInactiu;
	private JComboBox<Shift> comboBoxTorn;

	private JComboBox<String> comboBoxCurs;
	private String error;

	/**
	 * Creates the frame.
	 */

	public Group_SaveGroup(ClientConnectionHelper connectionHelper) {

		connectionHelper_ = connectionHelper;
		academicManagement = connectionHelper_.getAcademicManager();

		error = LanguageUtils.getMessage("client.management.error");

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 358);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JButton btnDesar = new JButton(
				LanguageUtils.getMessage("client.management.button.save"));
		btnDesar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					desar();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
		btnDesar.setBounds(10, 286, 89, 23);
		contentPane.add(btnDesar);

		JButton btnCancellar = new JButton(
				LanguageUtils.getMessage("client.management.button.cancel"));
		btnCancellar.setBounds(306, 286, 118, 23);
		contentPane.add(btnCancellar);
		btnCancellar.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		JPanel panel = new JPanel();
		panel.setBounds(10, 37, 414, 238);
		contentPane.add(panel);
		panel.setLayout(null);

		JLabel lblNomDelCurs = new JLabel(
				LanguageUtils.getMessage("client.management.button.nameCourse"));
		lblNomDelCurs.setBounds(10, 45, 118, 14);
		panel.add(lblNomDelCurs);

		JLabel lblMximDestudiants = new JLabel(
				LanguageUtils.getMessage("client.management.button.max"));
		lblMximDestudiants.setBounds(10, 115, 162, 14);
		panel.add(lblMximDestudiants);

		JLabel lblDataDinici = new JLabel(
				LanguageUtils.getMessage("client.management.button.startDate"));
		lblDataDinici.setBounds(10, 150, 87, 14);
		panel.add(lblDataDinici);

		JLabel lblDataFinal = new JLabel(
				LanguageUtils.getMessage("client.management.button.finalDate"));
		lblDataFinal.setBounds(10, 185, 74, 14);
		panel.add(lblDataFinal);

		JLabel lblEstatDelGrup = new JLabel(
				LanguageUtils
						.getMessage("client.management.button.groupStatus"));
		lblEstatDelGrup.setBounds(10, 220, 101, 14);
		panel.add(lblEstatDelGrup);

		textFieldMax = new JTextField();
		textFieldMax.setBounds(198, 112, 37, 20);
		panel.add(textFieldMax);
		textFieldMax.setColumns(10);

		textFieldStart = new JTextField();
		textFieldStart.setBounds(149, 144, 86, 20);
		panel.add(textFieldStart);
		textFieldStart.setColumns(10);

		textFieldEnd = new JTextField();
		textFieldEnd.setBounds(149, 179, 86, 20);
		panel.add(textFieldEnd);
		textFieldEnd.setColumns(10);

		comboBoxCurs = new JComboBox<String>();
		comboBoxCurs.setBounds(150, 42, 224, 20);
		panel.add(comboBoxCurs);

		try {
			comboBoxCurs.setModel(posarModel());
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}

		JLabel lblTorn = new JLabel(
				LanguageUtils.getMessage("client.management.button.shift"));
		lblTorn.setBounds(10, 80, 46, 14);
		panel.add(lblTorn);

		comboBoxTorn = new JComboBox<Shift>();
		comboBoxTorn.setModel(new DefaultComboBoxModel<Shift>(Shift.values()));
		comboBoxTorn.setBounds(149, 78, 101, 20);
		panel.add(comboBoxTorn);

		rdbtnActiu = new JRadioButton(
				LanguageUtils.getMessage("client.management.button.active"),
				true);
		rdbtnActiu.setBounds(149, 216, 86, 23);
		panel.add(rdbtnActiu);

		rdbtnInactiu = new JRadioButton(
				LanguageUtils.getMessage("client.management.button.inactive"),
				false);
		rdbtnInactiu.setBounds(242, 216, 109, 23);
		panel.add(rdbtnInactiu);

		ButtonGroup group = new ButtonGroup();
		group.add(rdbtnActiu);
		group.add(rdbtnInactiu);

		JLabel lblGestiDeGrups = new JLabel(
				LanguageUtils
						.getMessage("client.management.button.titleSaveGroup"));
		lblGestiDeGrups.setBounds(10, 11, 313, 14);
		contentPane.add(lblGestiDeGrups);
	}

	/**
	 * Reads the data from the JFrame to save the group
	 * 
	 * @throws RemoteException
	 * 
	 */
	public void desar() throws RemoteException {

		//gets the course from its name
		String name = null;
		name = (String) comboBoxCurs.getSelectedItem();
		Course course = academicManagement.findCourseByName(name);

		//gets maximum num of student and available dates
		int maxStudents = 0;
		try {
			maxStudents = Integer.valueOf(textFieldMax.getText());
		} catch (NumberFormatException e) {
			warn(LanguageUtils.getMessage("client.management.error.number"),
					error);

			return;
		}

		int availableSpots = Integer.valueOf(textFieldMax.getText());

		//gets the dates and makes sure they are in the correct format, and 
		//that initial dates precedes final date
		Date startDate = new Date();
		String str_dateStart = textFieldStart.getText();
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
		try {
			startDate = (Date) dateFormat.parse(str_dateStart);
		} catch (ParseException e) {
			warn(LanguageUtils.getMessage("client.management.error.dateStart"),
					error);

			return;
		}

		Date finalDate = new Date();
		String str_dateFinal = textFieldEnd.getText();

		try {
			finalDate = dateFormat.parse(str_dateFinal);

		} catch (ParseException e) {
			warn(LanguageUtils.getMessage("client.management.error.dateEnd"),
					error);

			return;
		}

		boolean dates = finalDate.before(startDate)
				|| startDate.after(finalDate);
		if (dates) {

			warn(LanguageUtils
					.getMessage("client.management.error.dateEndAfter"),
					error);

			return;

		}
		
		//gets the status and the shift

		boolean activeGroup = false;
		if (rdbtnActiu.isSelected()) {
			activeGroup = true;
		}

		Shift shift = (Shift) comboBoxTorn.getSelectedItem();

		//For all active groups, checks whether there is already another
		//group for the same course and shift.
		//If there isn't, we save the group.
		if (activeGroup) {
			Group group = null;
			group = academicManagement.findGroupByNameAndShift(name, shift);

			if (group != null) {
				warn(LanguageUtils
						.getMessage("client.management.error.alreadyExists"),
						error);
			} else {
				try {
					academicManagement.saveGroup(name, maxStudents,
							availableSpots, startDate, finalDate, activeGroup,
							course, shift);

					JOptionPane
							.showMessageDialog(
									null,
									LanguageUtils
											.getMessage("client.management.button.group.saved"),
									null, JOptionPane.INFORMATION_MESSAGE);

					dispose();
				} catch (NullPointerException e) {
					warn(LanguageUtils
							.getMessage("client.management.error.seleccourse"),
							error);
					return;

				}
			}
		} else {
			try {
				academicManagement.saveGroup(name, maxStudents, availableSpots,
						startDate, finalDate, activeGroup, course, shift);
				dispose();
			} catch (NullPointerException e) {
				warn(LanguageUtils
						.getMessage("client.management.error.seleccourse"),
						error);

				return;
			}

			JOptionPane.showMessageDialog(null, LanguageUtils
					.getMessage("client.management.button.group.saved"), null,
					JOptionPane.INFORMATION_MESSAGE);

		}
	}

	/**
	 * Populates the comboBoxModel with names of courses.
	 * 
	 * @return
	 * @throws RemoteException
	 */
	public DefaultComboBoxModel<String> posarModel() throws RemoteException {
		List<Course> courses;
		courses = academicManagement.listCourses();
		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
		model.addElement(null);
		for (int i = 0; i < courses.size(); i++) {
			model.addElement(courses.get(i).getCourseName());
		}
		return model;

	}

	/**
	 * Produces a warning JOptionPane
	 * 
	 * @param main
	 * @param sec
	 */
	public void warn(String main, String sec) {
		JOptionPane.showMessageDialog(null, main, sec,
				JOptionPane.ERROR_MESSAGE);
	}

}
